package com.intelligentmeterreadingsys.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.db.WaterListDaoImpl;

import dbhelper.DbTableName;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * 表册开机后自动定时下载服务
 * @author king
 *
 */
public class WaterlistUploadService extends Service{
	
	private static final String action="com.waterlist.upload";

	private Timer MyTimer=null;//定时器
	
	private String time="";
	
	private TimerTask MyTimertask=null;//定时任务
	
	private HttpClientServer server=null;//HTTP服务
	
	private SharedPreferenceUtil sp=null;//XML帮助类
	@Override
	public IBinder onBind(Intent intent) {
		
		return null;
	}

	@Override
	public void onCreate() {
		System.out.println("----------------");
	   initTimer();
	   startTimer();
	   server=new HttpClientServer(WaterlistUploadService.this);
	   sp=new SharedPreferenceUtil(WaterlistUploadService.this);
		super.onCreate();
	}

	@Override
	public void onDestroy() {
	   
		super.onDestroy();
	}
	
	
	/**
	 * 初始化定时器及任务
	 */
   public void initTimer(){
	   if(MyTimer==null){
		   MyTimer=new Timer();
	   }
	   if(MyTimertask==null){
		   MyTimertask=new TimerTask() {
			
			@Override
			public void run() {
			    System.out.println("时间到了");
				Message msg=MyHandle.obtainMessage();
				msg.what=1;
				MyHandle.sendMessage(msg);
				
			}
		};
	   }
	  
   }
   
   /**
    * 打开定时器
    */
   public void startTimer(){
	  
	   if(MyTimer!=null){
		   Calendar c=Calendar.getInstance();
		   c.set(Calendar.HOUR_OF_DAY, 1);
		   c.set(Calendar.MINUTE, 33);
		  
		   
		  MyTimer.schedule(MyTimertask, c.getTime());
	   }
   }
   
   /**
    * 关闭定时器
    */
   public void closeTimer(){
	   if(MyTimer!=null){
		   MyTimertask.cancel();
		   MyTimer.cancel();
		   
	   }
   }
	
   /**
    * 消息处理
    */
  Handler MyHandle=new Handler(){

	@Override
	public void handleMessage(Message msg) {
		
		if(msg.what==1){
			//upload();
			Toast.makeText(WaterlistUploadService.this, "测试", Toast.LENGTH_LONG).show();
		}
	}
	  
  };
  
  /**
   * 下载表册
   * @return
   */
  public String upload(){
	  String userid=sp.getValue("userid");
	  if(TextUtils.isEmpty(userid)){
		  return "";
	  }
	  Map<String, String> map=new HashMap<String, String>();
	  map.put("userid", userid);
	   String response=  server.doPost(map, RequestUrl.DownloadWaterList);
	   if(!response.equals("error")){
		   try {
			JSONObject obj=new JSONObject(response);
			//水表信息
			JSONArray waterinfo=obj.getJSONArray("waterinfo");
			List<ContentValues> listwaterinfo=new ArrayList<ContentValues>();
			for(int i=0;i<waterinfo.length();i++){
				JSONObject jb=waterinfo.getJSONObject(i);
				ContentValues value=new ContentValues();
				value.put("waternumber", jb.getString("waternumber"));
				value.put("waterlistid", jb.getString("waterlistid"));
				value.put("usernumber", jb.getString("usernumber"));
				value.put("wateradds", jb.getString("wateradds"));
				value.put("alarmlimit", jb.getDouble("alarmlimit"));
				value.put("lowalarmlimit", jb.getDouble("lowalarmlimit"));
				value.put("RFIDnumber", jb.getString("RFIDnumber"));
				value.put("latitude", jb.getDouble("latitude"));
				value.put("longitude", jb.getDouble("longitude"));
				value.put("lastmonthwater", jb.getDouble("lastmonthwater"));
				value.put("metercaliber", jb.getString("metercaliber"));
				value.put("lastdate", jb.getString("lastdate"));
				value.put("iscopystatus", "0");
				value.put("isupload", "0");			
				value.put("waterproperties", jb.getString("waterproperties"));
				
				listwaterinfo.add(value);
			}
			//用户信息
			JSONArray userinfo=obj.getJSONArray("userinfo");
			List<ContentValues> listuserinfo=new ArrayList<ContentValues>();
			for(int i=0;i<userinfo.length();i++){
				JSONObject jb=userinfo.getJSONObject(i);
				ContentValues value=new ContentValues();
				value.put("username", jb.getString("username"));
				value.put("usernumber", jb.getString("usernumber"));
				value.put("phone", jb.getString("phone"));
				value.put("useradds", jb.getString("useradds"));
				value.put("usertype", jb.getString("usertype"));
				value.put("status", jb.getString("status"));
				listuserinfo.add(value);
			}
			//月用水量信息
			JSONArray usewater=obj.getJSONArray("usewater");
			List<ContentValues> listusewater=new ArrayList<ContentValues>();
			for(int i=0;i<usewater.length();i++){
				JSONObject js=usewater.getJSONObject(i);
				 ContentValues value=new ContentValues();
				 value.put("waternumber",js.getString("waternumber") );
				 value.put("month", js.getString("moth"));
				 value.put("watercount", js.getString("watercount"));
				 listusewater.add(value);
			}
			//表册信息
			JSONArray waterlist=obj.getJSONArray("waterlist");
			List<ContentValues> listwaterlist=new ArrayList<ContentValues>();
			for(int i=0;i<waterlist.length();i++){
				JSONObject js=waterlist.getJSONObject(i);
				ContentValues value=new ContentValues();
				value.put("number", js.getString("number"));
				value.put("watercount", js.getString("watercount"));
				value.put("date", DateUtil.getBeforeDay(0));
			
				listwaterlist.add(value);
				
			}
			WaterListDaoImpl dao=new WaterListDaoImpl(WaterlistUploadService.this);
			boolean b=false;
			b=dao.insertALL(listwaterlist, DbTableName.WATERLIST);
			if(b){
				b=dao.insertALL(listuserinfo, DbTableName.USERINFO);
				if(b){
					b=dao.insertALL(listusewater, DbTableName.USEWATERINFO);
					if(b){
						b=dao.insertALL(listwaterinfo, DbTableName.WATERINFO);
					}
				}
			}
			dao.close();
			if(b){
				Respon("success");
				return "success";
			}else{
				Respon("error");
				return "error";
			}
		} catch (JSONException e) {
			Respon("error");
			return "error";
			
		}
		   
	   }
	return "error";
	  
  }
      
  /**
   * 下载后返回给服务器标志
   * @param message
   * @return
   */
      public boolean Respon(String message){
    	  boolean b=false;
    	  String userid=sp.getValue("userid");
    	  Map<String, String> maps=new HashMap<String, String>();
			maps.put("userid", userid);
			maps.put("message", message);
			String s=server.doPost(maps, RequestUrl.DownloadWaterList);
			if(!s.equals("error")){
				b=true;
			}
			return b;
      }
      
      public Date getDate(String time){
    	  Date date=null;
    	  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd:HH-mm");
    	 try {
			return date= format.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
      }
}
